#include "tpjsonreader.h"
#include <stdexcept>

using namespace std;

string PNG_FILENAME = "\"filename\": \"";
string FRAME_INFO = "\"frame\": {";
string PNG_SUFFIX = ".png";
string PNG_TOTAL_SIZE = "\"size\": {\"w\":";

#define INFO_FORMAT		    "\"frame\": {\"x\":%d,\"y\":%d,\"w\":%d,\"h\":%d},"
#define PNGTSIZE_FORMAT     "\"size\": {\"w\":%d,\"h\":%d},"

TPjsonReader::TPjsonReader():
picWidth(0),
picHeight(0)
{
    m_data.clear();
}
TPjsonReader::~TPjsonReader()
{
    for (auto it = m_data.begin(); it != m_data.end(); it++)
    {
        delete it->second;
    }
}


//f: which idx find the flag
void TPjsonReader::readFormatSheet(std::fstream& file, std::string& text,unsigned int f)
{
        unsigned int e = text.find(PNG_SUFFIX);
        if (e == string::npos)
        {
            throw invalid_argument("format error! .png find failed!");
        }
        string pngName = text.substr(f + PNG_FILENAME.length(), e - f - PNG_FILENAME.length());
        getline(file, text);
        e = text.find(FRAME_INFO);
        if (e == string::npos)
        {
            throw invalid_argument("format error! frame find failed!");
        }
        string infotext = text.substr(e);

        int x, y, w, h;
        int rev = sscanf(infotext.c_str(), INFO_FORMAT, &x, &y, &w, &h);
        if (rev != 4)
        {
            throw invalid_argument("get info error!");
        }

        Info* info = new Info();
        info->x = x;
        info->y = y;
        info->w = w;
        info->h = h;
        m_data[pngName] = info;
}

void TPjsonReader::readFormatTotalSize(std::string& text,unsigned int f)
{
    string totalSize = text.substr(f);
    int w,h;
    int rev = sscanf(totalSize.c_str(), PNGTSIZE_FORMAT, &w, &h);
    if (rev != 2)
    {
        throw invalid_argument("get size error!");
    }

    picWidth = w;
    picHeight = h;
}



void TPjsonReader::readjson(const char* filename)
{
    fstream file;
    file.open(filename);
    if (!file.is_open())
    {
        throw invalid_argument("can't open file!");
    }

    for (string text; getline(file, text);)
    {
        unsigned int f = text.find(PNG_FILENAME);
        if (f != string::npos)
        {
            readFormatSheet(file,text,f);
            continue;
        }

        f = text.find(PNG_TOTAL_SIZE);
        if (f != string::npos)
        {
            readFormatTotalSize(text,f);
        }
    }
}

void TPjsonReader::showInfo()
{
    for (auto it = m_data.begin(); it != m_data.end(); it++)
    {
        string name = it->first;
        Info* info = it->second;
        printf("name:%s[x:%d,y:%d,w:%d,h:%d]\n", name.c_str(), info->x, info->y, info->w, info->h);
    }
}
